package com.omesoft.hksnore.util.web;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Environment;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;


public class HttpUtil {
    public static String PICTURE_SAVE_PATH = "/omesoft/snorekiller/ask/";
    /** 数据库在SD卡上的存储路径 */
    public static String DB_SAVE_PATH = "/omesoft/snorekiller/databases/";

    // 获得Get请求对象request
    public static HttpGet getHttpGet(String url) {
        HttpGet request = new HttpGet(url);
        return request;
    }

    // 获得Post请求对象request
    public static HttpPost getHttpPost(String url) {
        HttpPost request = new HttpPost(url);
        HttpParams httpParameters = new BasicHttpParams(); // Set the timeout in
        // milliseconds
        // until a
        // connection is
        // established.
        int timeoutConnection = 3000;
        HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
        return request;
    }

    // 根据请求获得响应对象response
    public static HttpResponse getHttpResponse(HttpGet request) throws ClientProtocolException, IOException {
        HttpResponse response = new DefaultHttpClient().execute(request);
        return response;
    }

    // 根据请求获得响应对象response
    public static HttpResponse getHttpResponse(HttpPost request) throws ClientProtocolException, IOException {
        HttpResponse response = new DefaultHttpClient().execute(request);
        return response;
    }

    // 发送Post请求，获得响应查询结果
    public static String queryStringForPost(String url) {
        url = DataCheckUtil.stringFormat(url);
        // Log.v("test", "url:"+url);
        String result = null;

        try {
            HttpPost request = new HttpPost(url);
            HttpParams httpParameters = new BasicHttpParams();
            int timeoutConnection = 10 * 1000;
            HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
            int timeoutSocket = 5000;
            HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
            DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
            // 获得响应对象
            HttpResponse response = httpClient.execute(request);

            // 判断是否请求成功
            if (response.getStatusLine().getStatusCode() == 200) {
                // 获得响应
                result = EntityUtils.toString(response.getEntity());
                return result;
            }
        } catch (ClientProtocolException e) {
            // Log.v("test", "e.getMessage():" + e.getMessage());
            e.printStackTrace();
            return null;

        } catch (IOException e) {
            // Log.v("test", "e.getMessage():" + e.getMessage());
            e.printStackTrace();
            return null;
        }
        return null;
    }



    public static boolean isNumeric(String str) {
        for (int i = str.length(); --i >= 0;) {
            int chr = str.charAt(i);
            if (chr < 48 || chr > 57)
                return false;
        }
        return true;
    }


    /**
     * 根据URL转化成Bitmap
     *
     * @param url
     * @return Bitmap
     */
    public static Bitmap getHttpBitmap(String url) {
        Bitmap bitmap = null;
        // 以最省内存的方式读取本地资源的图片
        BitmapFactory.Options opt = new BitmapFactory.Options();
        opt.inPreferredConfig = Bitmap.Config.RGB_565;
        opt.inPurgeable = true;
        opt.inInputShareable = true;
        // 加载本地资源文件
        if (url.contains("head")) {
            return bitmap;
        } else {
            try {
                // 判断图片在本地是否存在
                // //Log.v("test", "判断图片在本地是否存在");
                String temp[] = url.split("/");
                String fileName = temp[temp.length - 1];
                String sdPath = Environment.getExternalStorageDirectory().toString();// 获取跟目录
                String filePath = sdPath + PICTURE_SAVE_PATH + fileName;
                File file = new File(filePath);
                if (!file.exists()) {
                    // Log.v("test", "~~~~~~图片不存在本地");
                    URL myFileURL;
                    myFileURL = new URL(url);
                    // 获得连接
                    HttpURLConnection conn = (HttpURLConnection) myFileURL.openConnection();

                    // 设置超时时间为6000毫秒，conn.setConnectionTiem(0);表示没有时间限制
                    conn.setConnectTimeout(6000);
                    // 连接设置获得数据流
                    conn.setDoInput(true);
                    // 不使用缓存
                    conn.setUseCaches(false);
                    // 得到数据流
                    InputStream is = conn.getInputStream();

                    // 判断SD卡存在
                    if (!checksdCardExist()) {
                        // Log.v("test", "~~~~~~SD卡不存在 从网络返回图片");
                        BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
                        bitmapOptions.inSampleSize = 4;
                        bitmap = BitmapFactory.decodeStream(is, null, bitmapOptions);
                        return bitmap;
                    } else {
                        // Log.v("test", "~~~~~~SD卡存在");
                        // 将图片保存到SD卡指定目录
                        saveBitmapToSD(is, filePath);
                    }

                }
                // Log.v("test", "~~~~~~~~从本地获取图片");
                bitmap = BitmapFactory.decodeFile(file.getPath(), opt);

            } catch (Exception e) {
                // Log.e("test", "~~~~~~异常 返回'加载失败'图片");
                // 如果读取图片异常就返回一张“图片加载失败”的图片
                // //Log.e("test", e.getMessage());
                // BitmapFactory.Options options = new BitmapFactory.Options();
                // opt.inPreferredConfig = Bitmap.Config.RGB_565;
                // opt.inPurgeable = true;
                // opt.inInputShareable = true;
                // bitmap =
                // BitmapFactory.decodeResource(mContext.getResources(),
                // R.drawable.picture_loading_fail, opt);
                bitmap = null;
            }
            return bitmap;
        }
    }

    // 复制
    private static void saveBitmapToSD(InputStream myInput, String outFilePath) {
        // Log.v("test", "~~~~~~ copy 把图片保存在本地");
        try {
            File file = new File(outFilePath);
            if (!file.exists()) {
                // Log.v("test", "~~~~~~ copy 创建目录");
                file.getParentFile().mkdirs();
            }
            // 用流的形式把数据库文件添加到指定的目录里
            OutputStream myOutput = new FileOutputStream(outFilePath);
            byte[] buffer = new byte[1024];
            int length;
            while ((length = myInput.read(buffer)) > 0) {
                myOutput.write(buffer, 0, length);// 复制
            }
            myOutput.flush();
            myOutput.close();
            myInput.close();
            // Log.v("test", "~~~~~~图片保存成功outFilePath:" + outFilePath);
        } catch (IOException e) {
            // Log.v("test", "~~~~~~图片保存失败outFilePath:" + outFilePath);
            e.printStackTrace();
        }
    }

    //
    // /** 判断sd卡是否存在 */
    public static boolean checksdCardExist() {
        boolean mExternalStorageAvailable = false;
        boolean mExternalStorageWriteable = false;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            // We can read and write the media
            mExternalStorageAvailable = mExternalStorageWriteable = true;
            // Log.v("test",
            // " mExternalStorageAvailable = mExternalStorageWriteable = true");

        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            // We can only read the media
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
            // Log.v("test",
            // "This Application needs a writable external storage (sdcard)");
        } else {
            // Something else is wrong. It may be one of many other states, but
            // all we need
            // to know is we can neither read nor write
            mExternalStorageAvailable = mExternalStorageWriteable = false;
            // Log.v("test",
            // "This Application needs a mounted external storage (sdcard)");

        }

        boolean sdCardExist = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        return sdCardExist;

    }
    /**
     * 获取外网ip
     *
     * @param
     *
     * @param
     * @return
     * @throws Exception
     */
    public static String GetNetIp(Context context) throws Exception {
        // 获取wifi服务
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        String ip = null;
        // 判断wifi是否开启
        if (wifiManager.isWifiEnabled()) {
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            int ipAddress = wifiInfo.getIpAddress();
            ip = (ipAddress & 0xFF) + "." + ((ipAddress >> 8) & 0xFF) + "." + ((ipAddress >> 16) & 0xFF)
                    + "." + (ipAddress >> 24 & 0xFF);
        } else {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en
                    .hasMoreElements();) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr
                        .hasMoreElements();) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                        ip = inetAddress.getHostAddress().toString();
                        break;
                    }
                }
            }

        }
        return ip;
    }

    private static String getIpFromOutWeb(URL infoUrl) throws Exception {
        StringBuilder strber = null;
        InputStream inStream = null;
        URLConnection connection = infoUrl.openConnection();
        HttpURLConnection httpConnection = (HttpURLConnection) connection;
        int responseCode = httpConnection.getResponseCode();
        if (responseCode == HttpURLConnection.HTTP_OK) {
            inStream = httpConnection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inStream, "utf-8"));
            strber = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                strber.append(line + "\n");
            }
            inStream.close();
        }
        return strber.toString();
    }

}
